import json

import requests
import hashlib
import uuid
import random
import time


def gen_nonce_old():
    i2 = 16
    string_buffer = []
    for i3 in range(i2):
        string_buffer.append(
            "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[random.randint(0, 61)])
    string_buffer = ''.join(string_buffer)
    return string_buffer


# 生成nonce
def gen_nonce_new(i2):
    stringBuffer = ""
    for i3 in range(i2):
        stringBuffer += "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[random.randint(0, 61)]
    return stringBuffer


# 生成sign值
def gen_sign(info, url):
    # 因为java有排序 在python中需要sorted来调整,sorted是根据acill码点进行排序
    result = "&".join([f"{key}={info[key]}" for key in sorted(info.keys())])
    # print("这是经过排序后的格式:", result)

    # 加密前的明文
    str_sign = url + result + 'aA4@ud^926U(}^r9'
    # print("这是加密前的明文:", str_sign)

    obj = hashlib.md5()
    byte = obj.update(str_sign.encode('utf-8'))
    hex_string = obj.hexdigest()

    # 对二进制进行hash
    hash_bytes = obj.digest()

    # 将字节字符串转换为字符数组
    hash_array = list(hash_bytes)

    a = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]

    def b(byte):
        i2 = int(byte) // 16
        # print(i2)
        sb = ''
        strArr = a
        sb += strArr[i2]
        sb += strArr[byte % 16]
        return sb

    def c(bArr):
        stringBuffer = ""
        for byte in bArr:
            stringBuffer += b(byte)
        return stringBuffer

    # sign值：
    g_sign = c(hash_array)
    return g_sign


categories = [{'name': '热销总榜', 'ID': '5666'}, {'name': '每日爆款清单', 'ID': '5667'}, {'name': '数码家电 ‧ 热销榜', 'ID': '5658'},
        {'name': '男装 ‧ 热销榜', 'ID': '5657'}, {'name': '居家日用 ‧ 热销榜', 'ID': '5662'}, {'name': '美食 ‧ 热销榜', 'ID': '5660'},
        {'name': '鞋品 ‧ 热销榜', 'ID': '5661'}, {'name': '女装 ‧ 热销榜', 'ID': '5665'}, {'name': '美妆 ‧ 热销榜', 'ID': '5663'},
        {'name': '文娱车品 ‧ 热销榜', 'ID': '5659'}, {'name': '户外运动 ‧ 热销榜', 'ID': '5653'}, {'name': '母婴 ‧ 热销榜', 'ID': '5664'},
        {'name': '配饰 ‧ 热销榜', 'ID': '5654'}, {'name': '内衣 ‧ 热销榜', 'ID': '5656'}, {'name': '家装家纺 ‧ 热销榜', 'ID': '5652'},
        {'name': '箱包 ‧ 热销榜', 'ID': '5655'}]

for item in categories:
    category_name = item['name']
    category_id = item['ID']

    print(category_id)

    # 获取UUID
    x_device_udid = uuid.uuid4()
    x_device_uuid = str(x_device_udid).replace("-", "")

    # 生成/nodes/5666的nonce
    nodes_nonce = gen_nonce_new(16)

    # 获取nodes_time的时间戳
    nodes_time = str(int(time.time()))

    # nodes_info的
    nodes_info = {
        "last_items_count": 0,
        "nonce": nodes_nonce,
        "timestamp": nodes_time,
    }

    # url要参与sign的生成
    # url_data = f'https://api2.tophub.app/nodes/{category_id}'
    url_data = f'https://api2.tophub.app/nodes/181'
    print(url_data)

    # 获取nodes_sign签名
    nodes_sign = gen_sign(nodes_info, url_data)

    # 构造请求头
    hearder = {
        "authorization": "7761d7f192092ff72f8824b2d9071a60",
        "accept": "application/vnd.tophub.v1+json",
        "user-agent": "TophubApp/1.0 Mozilla/5.0 (Linux; Android 11; Pixel 2 XL Build/RP1A.201005.004.A1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/118.0.0.0 Mobile Safari/537.36",
        "x-network-type": "NETWORK_WIFI",
        "x-app-version": "18",
        "x-app-package-name": "today.tophub.app",
        "x-app-version-name": "1.9.3",
        "x-device-uuid": "164051e9f063e7976e5bc23397460a1f",
        "x-device-model": "Pixel2XL",
        "x-device-udid": "164051e9-f063-3797-ae5b-c23397460a1f",
        "accept-encoding": "gzip"
    }

    # 请求参数
    params = {
        "last_items_count": 0,
        "nonce": nodes_nonce,
        "sign": nodes_sign,
        "timestamp": nodes_time
    }


    try:
        nodes_res = requests.get(url=url_data, params=params, headers=hearder, timeout=10)
        print(nodes_res.url)
        print(nodes_res.status_code, '\n', nodes_res.json())
        # with open('./data.json', 'w') as file:
        #     json.dump(nodes_res.json(), file)

    except Exception as e:
        print("获取数据失败，请重试！！！！", e)

    input("按键到下一条*******************************")